/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')
// 引入 await-to-js 库，用于处理异步操作
const { to } = require('await-to-js')
// 引入 moment 库，用于日期和时间操作
const moment = require('moment')
// 引入 fs 模块，用于文件系统操作
const fs = require('fs')

// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 引入 esm 库，用于在 Node.js 中支持 ES6 模块
const esm = require('esm')
// 使用 esm 配置来加载模块
const requireModule = esm(module)

// 地区
const { region } = requireModule(path.join(__dirname, '../src/utils/modules/settings.js'))

// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')

// 读取并构建 fixedGroupMapObject
const { finalGroupMap, flatGroupMap, groupArray } = requireModule(path.join(HELPERS_DIR, 'readGroup.js'))

// 计算准确统计
const { calcAccuracySummary, ACCURACY_SUMMARY_CN_MAP } = require(path.join(HELPERS_DIR, 'calcAccuracySummary.js'))
const { filterForecaArray } = require(path.join(HELPERS_DIR, 'filterForecaArray.js'))

const { getLuckAndForecastGroupNames } = require(path.join(HELPERS_DIR, 'getLuckAndForecastGroupNames.js'))

// 读取所有数据
const { readAllValues } = require(path.join(HELPERS_DIR, 'readAllValues.js'))

const allValues = readAllValues(region).slice(0, 200)
// console.log(allValues.length)

const allNumbers = Array.from({ length: 49 }, (_, i) => i + 1).map((num) => (num < 10 ? `0${num}` : `${num}`))

// console.log(allNumbers)
// console.log(flatGroupMap)

// 初始化目标对象，每个数字对应空对象
const numberGroupMap = allNumbers.reduce((acc, num) => {
  acc[num] = {}
  return acc
}, {})

// 遍历每个分组
Object.entries(flatGroupMap).forEach(([groupName, groups]) => {
  // groups是包含两个子数组的数组
  groups.forEach((group, groupIndex) => {
    group.forEach((num) => {
      // 将数字转为两位字符串，如2 -> '02'
      const numStr = num.toString().padStart(2, '0')
      // 确保该数字在映射中存在
      if (numberGroupMap[numStr]) {
        // 将分组名称和子数组索引存入
        numberGroupMap[numStr][groupName] = groupIndex
      }
    })
  })
})

const r1 = _.mapValues(flatGroupMap, (value, key) => {
  return {
    accuracyList: [],
    group_type: undefined
  }
})

// console.log(r1)
// console.log(allValues.length)
// console.log(Object.keys(flatGroupMap).length)

groupArray.forEach((item) => {
  const key = item.group_name
  r1[key].group_type = item.group_type
  r1[key].accuracyList = allValues.map((item, index) => {
    if (index === 0) {
      return 1
    } else {
      // index 从 1 开始
      const prevNumber = allValues[index - 1].number
      const prevIndex = numberGroupMap[prevNumber][key]
      const prevGroup = flatGroupMap[key][prevIndex]
      return prevGroup.map(Number).includes(Number(item.number)) ? 0 : 1
    }
  })
})

// console.log(Object.keys(r1).length)
// console.log(r1['SIX_ASCENDING_GROUPS'])

// 写入文件
/*
console.time('写入文件')
const sortResults = (a, b) => {
  if (b.stats.accuracyRate !== a.stats.accuracyRate) {
    return b.stats.accuracyRate - a.stats.accuracyRate // accuracy_rate 降序
  }
  return a.stats.maxConsecutiveIncorrect - b.stats.maxConsecutiveIncorrect // max_consecutive_incorrect 升序
}

const r2 = allValues.map((item, index) => {
  if (index < 2) {
    return {
      ...item,
      kill_array: [],
      lucky_array: [],
      red_continuous_limit_2: [],
      green_rebound_red_non_continuous: [],
      green_continuous: []
    }
  } else {
    const currentAccuracyMap = _.chain(r1)
      .mapValues((value, key) => {
        const currentAccuracyList = value.accuracyList.slice(0, index + 1)
        const stats = calcAccuracySummary(currentAccuracyList)
        return {
          accuracy_array: currentAccuracyList,
          stats
        }
      })
      .value()
    const currentGroupArray = Object.keys(currentAccuracyMap).map((key) => ({
      groupName: key,
      groupType: r1[key].group_type,
      ...currentAccuracyMap[key]
    }))

    // 过滤预测数组
    const { redContinuousLimit2Group, greenReboundRedNonContinuousGroup, greenContinuousGroup } = filterForecaArray(
      currentGroupArray,
      sortResults
    )

    if (index === 49) {
      fs.writeFileSync(path.join(__dirname, 'redContinuousLimit2Group.json'), JSON.stringify(redContinuousLimit2Group, null, 2), 'utf-8')
      fs.writeFileSync(path.join(__dirname, 'greenReboundRedNonContinuousGroup.json'), JSON.stringify(greenReboundRedNonContinuousGroup, null, 2), 'utf-8')
      fs.writeFileSync(path.join(__dirname, 'greenContinuousGroup.json'), JSON.stringify(greenContinuousGroup, null, 2), 'utf-8')
    }

    // 获取幸运和杀前组组名
    const { kill_array, lucky_array, red_continuous_limit_2, green_rebound_red_non_continuous, green_continuous } =
      getLuckAndForecastGroupNames(
        redContinuousLimit2Group,
        greenReboundRedNonContinuousGroup,
        greenContinuousGroup,
        item,
        numberGroupMap,
        flatGroupMap
      )

    return {
      ...item,
      kill_array,
      lucky_array,
      red_continuous_limit_2,
      green_rebound_red_non_continuous,
      green_continuous
    }
  }
})

// 写入到文件 steps_01_result.json
fs.writeFileSync(path.join(__dirname, 'r2.json'), JSON.stringify(r2, null, 2), 'utf-8')
console.timeEnd('写入文件')

//*/

// 异步方式（非阻塞）
/*

fs.readFile(path.join(__dirname, 'r2.json'), 'utf8', (err, jsonString) => {
  if (err) {
    console.error('读取文件失败:', err)
    return
  }
  try {
    const data = JSON.parse(jsonString)
    // console.log('成功读取 JSON 数据:', data.at(-1));
    const allList = data.map((item, index) => {
      if (index < 3) {
        return {
          ...item,
          accuracy: 1
        }
      } else {
        const prev = data[index - 1]
        return {
          ...item,
          accuracy: prev.lucky_array.includes(item.number) ? 1 : 0
        }
      }
    })

    const accuracyList = allList.map((item) => item.accuracy)

    const accuracySummary = calcAccuracySummary(accuracyList)
    // 打印中文
    Object.entries(ACCURACY_SUMMARY_CN_MAP).forEach(([key, value]) => {
      console.log(`${value}: ${accuracySummary[key]}`)
    })
  } catch (parseErr) {
    console.error('解析 JSON 失败:', parseErr)
  }
})

//*/

// -------------------------------------------------------------------------------

console.time('计算结束')

const sortResults = (a, b) => {
  if (b.stats.accuracyRate !== a.stats.accuracyRate) {
    return b.stats.accuracyRate - a.stats.accuracyRate // accuracy_rate 降序
  }
  return a.stats.maxConsecutiveIncorrect - b.stats.maxConsecutiveIncorrect // max_consecutive_incorrect 升序
}

const r2 = allValues.map((item, index) => {
  if (index < 2) {
    return {
      ...item,
      kill_array: [],
      lucky_array: [],
      red_continuous_limit_2: [],
      green_rebound_red_non_continuous: [],
      green_continuous: []
    }
  } else {
    const currentAccuracyMap = _.chain(r1)
      .mapValues((value, key) => {
        const currentAccuracyList = value.accuracyList.slice(0, index + 1)
        const stats = calcAccuracySummary(currentAccuracyList)
        return {
          accuracy_array: currentAccuracyList,
          stats
        }
      })
      .value()
    const currentGroupArray = Object.keys(currentAccuracyMap).map((key) => ({
      groupName: key,
      groupType: r1[key].group_type,
      ...currentAccuracyMap[key]
    }))

    // 过滤预测数组
    const { redContinuousLimit2Group, greenReboundRedNonContinuousGroup, greenContinuousGroup } = filterForecaArray(
      currentGroupArray,
      sortResults
    )
    // 获取幸运和杀前组组名
    const { kill_array, lucky_array, red_continuous_limit_2, green_rebound_red_non_continuous, green_continuous } =
      getLuckAndForecastGroupNames(
        redContinuousLimit2Group,
        greenReboundRedNonContinuousGroup,
        greenContinuousGroup,
        item,
        numberGroupMap,
        flatGroupMap,
        index
      )

    return {
      ...item,
      kill_array,
      lucky_array,
      red_continuous_limit_2,
      green_rebound_red_non_continuous,
      green_continuous
    }
  }
})

const data = r2
// console.log('成功读取 JSON 数据:', data.at(-1));
const allList = data.map((item, index) => {
  if (index < 3) {
    return {
      ...item,
      accuracy: 1
    }
  } else {
    const prev = data[index - 1]
    return {
      ...item,
      accuracy: prev.lucky_array.includes(item.number) ? 1 : 0
    }
  }
})

const accuracyList = allList.map((item) => item.accuracy)

console.log(accuracyList)

const accuracySummary = calcAccuracySummary(accuracyList)
// 打印中文
Object.entries(ACCURACY_SUMMARY_CN_MAP).forEach(([key, value]) => {
  console.log(`${value}: ${accuracySummary[key]}`)
})

console.timeEnd('计算结束')
